let curUnionID = null;

function createList(pageNo = 1, pageSize = 10) {

    let matchData = {
        'isRobot': true,
        'unionID': curUnionID
    };
    let selectType = $("#selectType").val();
    if (selectType && selectType != '0') {
        matchData['gameType'] = selectType;
    }
    var start = (pageNo - 1) * pageSize;
    apiAdminGetRecord("userModel", start, pageSize, matchData, function (data) {
        if (data.code === 0) {
            setTimeout(() => {
                $('#robotData').bootstrapTable('load', data.msg);
            }, 200)
        }
    });
}


function addType() {

    var row = $("#robotData").bootstrapTable('getSelections');
    if (row.length > 0) {
        let list = [];
        for (let i = 0; i < row.length; i++) {
            list.push(row[i].uid);
        }
        $("#reAddUserID").val(list);
        $("#reAddUserID").attr("disabled", true);
        $('#addType').modal('show');
    } else {
        $.modal({
            body: '请先选择机器人'
        });
    }
}



function addRobotToGameType() {

    let uid = $("#reAddUserID").val();
    let gameType = $("#reGameType").val();
    let addWinRate = $("#addWinRate").val() || 0;
    let addWinType = $("#addWinType").val();
    let robotType = $("#robotType").val();
    let beginTime = $("#beginTime").val() || 0;
    let endTime = $("#endTime").val() || 0;
    let winScore = $("#winScore").val() || 0;
    let loseScore = $("#loseScore").val() || 0;
    $('#addType').modal('hide');
    let updateInfo = {
        gameType,
        winRate: addWinRate,
        winType: addWinType,
        robotType,
        beginTime,
        endTime,
        winScore,
        loseScore
    }
    apiReGameType(uid, JSON.stringify(updateInfo), () => {
        var currentPage = $('#robotData').bootstrapTable('getOptions').pageNumber
        createList(currentPage);
    });
}




//启用 停用机器人
function robotBand(uid, isBind) {

    apiRobotBand(uid, isBind, () => {
        $('#robotData').bootstrapTable('refresh', {});
    });

}

function robotReback(uid) {


    Swal.fire({
        title: '确定回收机器人？',
        // text: "联盟删除后无法恢复，请谨慎操作",
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#198754',
        cancelButtonColor: '#d93444',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
    }).then((result) => {
        if (result.isConfirmed) {
            apiRebackRobot(uid, () => {
                var currentPage = $('#robotData').bootstrapTable('getOptions').pageNumber
                createList(currentPage);
            });
        }
    });


}

function addOrderUinon(uid) {

    $("#addUserID").val(uid);
    $("#addUserID").attr("disabled", "true");
    $('#addOrder').modal('show');
}


//将机器人加到联盟中
function addRobotToUnion() {

    let uid = $("#addUserID").val();
    let unionID = $("#addUnionID").val();
    $("#addUserID").val("");
    $("#addUnionID").val("");
    $('#addOrder').modal('hide');
    apiRobotToUnion(uid, unionID, () => {
        $('#robotData').bootstrapTable('refresh', {});
    });

}


function selectGameType() {

    let select = $("#selectType");
    let reGameType = $("#reGameType");

    for (let key in enumeration.gameType) {
        let type = enumeration.gameType[key];
        select.append("<option value='" + type + "'>" + enumeration.gameName[type] + "</option>");
        reGameType.append("<option value='" + type + "'>" + enumeration.gameName[type] + "</option>");
    }

}

$(document).ready(function () {

    $(function () {

        var parameters = parseQueryString(window.location.href);
        curUnionID = parameters.unionID;

        selectGameType();
        //数据表格初始化
        $('#robotData').bootstrapTable({
            striped: true, // 是否显示行间隔色
            pageNumber: 1, // 初始化加载第一页
            pagination: true, // 是否分页
            clickToSelect: true,
            theadClasses: "thead-light", //这里设置表头样式
            sidePagination: 'server', // server:服务器端分页|client：前端分页
            pageSize: 10, // 单页记录数
            pageList: [10, 20, 30],
            dataField: "recordArr",
            totalField: "totalCount",
            buttonsClass: 'light',
            buttonsPrefix: 'btn',
            showRefresh: false, // 刷新按钮
            onPageChange: function (number, size) {
                createList(number, size);
            },
            queryParams: function (params) { // 上传服务器的参数
                var temp = { //如果是在服务器端实现分页，limit、offset这两个参数是必须的
                    limit: params.limit, // 每页显示数量
                    offset: params.offset, // SQL语句起始索引
                };
                return temp;
            },
            onPostBody: function () {
                //重新启用弹出层,否则formatter格式化函数返回的html字符串上的tooltip提示不生效
                $('[data-bs-toggle="tooltip"]').each(function (i, el) {
                    new bootstrap.Tooltip(el)
                })
            },
            queryParams: function (params) { // 上传服务器的参数
                var temp = { //如果是在服务器端实现分页，limit、offset这两个参数是必须的
                    limit: params.limit, // 每页显示数量
                    offset: params.offset, // SQL语句起始索引
                };
                return temp;
            },
            columns: [{
                checkbox: true,
                align: "center",
                valign: "middle",
            }, {
                title: 'id',
                field: '_id',
                visible: false
            },
            {
                title: 'UID',
                width: 100,
                align: "center",
                valign: "middle",
                field: 'uid',
            }, {
                title: '昵称',
                width: 100,
                align: "center",
                valign: "middle",
                field: 'nickname',

            }, {
                title: '头像',
                field: 'avatar',
                width: 100,
                align: "center",
                valign: "middle",
                formatter: avaterImg
            }, {
                title: '联盟ID',
                width: 100,
                align: "center",
                valign: "middle",
                field: 'unionID',
                sortable: true,
                visible: false,
                order: "asc",

            }, {
                title: '类型',
                width: 100,
                align: "center",
                valign: "middle",
                field: 'robotType',
                formatter: robotTypeSet
            }, {
                title: '游戏类型',
                width: 100,
                align: "center",
                valign: "middle",
                field: 'gameType',
                formatter: gameTypeSet
            },
            {
                title: '控制类型',
                width: 100,
                align: "center",
                valign: "middle",
                field: 'winType',
                formatter: winTypeSet
            },
            {
                title: '输赢比例',
                field: 'winRate',
                width: 100,
                align: "center",
                valign: "middle",
            },
            {
                title: '开始时间',
                width: 100,
                align: "center",
                valign: "middle",
                field: 'beginTime',
                formatter: function (value) {
                    if (value) {
                        return value + ':00'
                    }

                },
            },
            {
                title: '结束时间',
                width: 100,
                align: "center",
                valign: "middle",
                field: 'endTime',
                formatter: function (value) {
                    if (value) {
                        return value + ':00'
                    }
                },
            },
            {
                title: '最大赢分',
                width: 100,
                align: "center",
                valign: "middle",
                field: 'winScore',

            },
            {
                title: '最大输分',
                width: 100,
                align: "center",
                valign: "middle",
                field: 'loseScore',
            }, {
                title: 'IP地址',
                width: 150,
                align: "center",
                valign: "middle",
                field: 'lastLoginIP'
            }, {
                field: 'createTime',
                align: "center",
                valign: "middle",
                width: 150,
                visible: false,
                title: '创建时间',
                formatter: function (value) {
                    return new Date(value).toLocaleString();
                }
            },
            {
                title: '操作',
                width: 100,
                align: "center",
                valign: "middle",
                formatter: option
            }
            ]
        });
        createList(1);
    })

    //机器人控制类型0：正常 1：输 2：赢
    function winTypeSet(value, row, index) {
        if (value == 2) {
            return '赢';
        } else if (value == 1) {
            return '输';
        } else {
            return '正常';
        }
    }


    // 定义删除、更新按钮
    function robotTypeSet(value, row, index) {

        if (value == 0) {
            return '气氛组';
        } else if (value == 1) {
            return '被动陪打';
        } else if (value == 2) {
            return '主动陪打';
        } else {
            return '暂未设置';
        }
    }

    function gameTypeSet(value, row, index) {

        if (value == 0) {
            return '全部';
        } else if (value == -1) {
            return '暂未投放';
        } else if (value >= 1) {
            return enumeration.gameName[value]
        } else {
            return "未设置"
        }
    }



    // 定义删除、更新按钮
    function avaterImg(value, row, index) {
        var htm = "";
        htm = `<img  style="width: 40px ; height: 40px;"  src="${value}" class="img-thumbnail" >`;
        return htm;
    }

    // 定义删除、更新按钮
    function option(value, row, index) {
        var htm = "";
        htm += `<button type="button" class="btn btn-light"  data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="回收机器人" onClick="robotReback(${row.uid})"><i class="bi bi-recycle fs-5 text-danger"></i></button>`;
        return htm;
    }

});